package com.um.jdy.tcp.downlink;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.um.jdy.tcp.uplink.UplinkCommand;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 上行命令工厂
 *
 * @author 甘天伟
 * @since 2022/11/2
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
public class DownlinkCommandFactory {

    private static volatile Map<String, Class<?>> commandClasses = null;

    private static Map<String, Class<?>> getCommandClasses() {
        if (commandClasses == null) {
            synchronized (DownlinkCommandFactory.class) {
                if (commandClasses == null) {
                    commandClasses = new ConcurrentHashMap<>();
                    String packageName = DownlinkCommandFactory.class.getPackage().getName();
                    Set<Class<?>> classes = ClassUtil.scanPackage(packageName, clazz -> clazz.getSimpleName().startsWith("Cmd"));
                    classes.forEach(clazz -> commandClasses.put(clazz.getSimpleName().substring(3, 5), clazz));
                }
            }
        }
        return commandClasses;
    }

    public static DownlinkCommand createCommand(String json) {
        try {
            DownlinkCommand command = JSON.parseObject(json, DownlinkCommand.class);
            String commandKey = StrUtil.padPre(command.getCmd().toString(), 2, '0');
            Class<?> clazz = getCommandClasses().get(commandKey);
            if (clazz != null) {
                command = (DownlinkCommand) JSON.parseObject(json, clazz);
                return command;
            }
        } catch (Exception e) {
            //log.e ("创建命令实例出错", e);
        }
        return null;
    }



//    public static void main(String[] args) {
//        String json = "{\"AUTOOPEN\":1,\"CMD\":3,\"DEVICE\":\"865281053195137\",\"PORT\":1,\"POWER\":3500,\"SEQ\":\"2505071741292276080\",\"TIME\":492}";
//        DownlinkCommand cmd = createCommand(json);
//        System.out.println(JSON.toJSONString(cmd));
//    }
}
